import api from '@/api'
import loginApi from '@/api/login'
import db from '@/util/localStorage'
import permissionsApi from '@/api/permissions'

const state = {
    user: db.get('user'),
    account: db.get('account') || '',
    token: db.get('token') || '',
    refreshToken: db.get('refreshToken') || '',
    failure_time: db.get('failure_time') || '',
    permissions: []
}
// 获取token 是否有效
const getters = {
    isLogin: state => {
        let retn = false
        if (state.token) {
            let unix = Date.parse(new Date())
            if (unix < state.failure_time) {
                retn = true
            }
        }
        return retn
    }
}

const actions = {
    login({commit}, data) {
        return new Promise((resolve, reject) => {
            // 通过 mock 进行登录
            loginApi.login(data).then(res => {
                commit('setUserData', res.data.data)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    logout({commit}) {
        commit('removeUserData')
        commit('menu/invalidRoutes', null, {root: true})
    },
    // 获取我的权限
    getPermissions({state, commit}) {
        return new Promise(resolve => {
            // 获取路由菜单
            permissionsApi.userMenu().then(res => {
                console.log(res)
            })
            resolve()
            // 通过 mock 获取权限
            /*            api.get('mock/member/permission', {
                params: {
                    account: state.account
                }
            }).then(res => {
                commit('setPermissions', res.data.permissions)
                resolve(res.data.permissions)
            })*/

        })
    }
}

const mutations = {
    setUserData(state, data) {
        let user = {
            id: data.userId,
            account: data.account,
            name: data.name,
            avatar: data.avatar,
            workDescribe: data.workDescribe
        }
        db.save('user', user)
        db.save('account', data.account)
        db.save('token', data.token)
        db.save('failure_time', Date.parse(data.expiration))
        state.account = data.account
        state.token = data.token
        state.failure_time = Date.parse(data.expiration)
    },
    removeUserData(state) {
        db.remove('user')
        db.remove('account')
        db.remove('token')
        db.remove('failure_time')
        state.account = ''
        state.token = ''
        state.failure_time = ''
    },
    setPermissions(state, permissions) {
        state.permissions = permissions
    }
}

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
}
